from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = datetime.now()
        self.friends = []
        self.books = []

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime(format='%Y-%m-%d %H:%H:%S')

    #自嵌套-->方式二：使用构造器自身作为外键的关联方式，并指定序列化的字段
    # friends = fields.Nested("self",only=("name", ), many=True)

    # 自嵌套-->方式二的另一种写法：使用构造器自身作为外键的关联方式，并指定序列化的字段
    friends = fields.Nested(lambda: UserSchema(many=True, only=("name",)), dump_only=True)

    # friends = fields.Pluck("self", "name", many=True) # 方式三：使用Pluck字段可以用单个值来替换嵌套的数据。

@app.route("/")
def index():
    #自嵌套
    user0 = User(name="小明",email="123@qq.com")
    user1 = User(name="小红",email="123@qq.com")
    user2 = User(name="小白",email="123@qq.com")
    user3 = User(name="小黑",email="123@qq.com")
    user0.friends=[user1,user2,user3]
    us = UserSchema()
    user0 = us.dump(user0)
    print(user0)
    """
    打印结果：
        {
            'created_at': '2021-03-06 00:00:15', 
            'email': '123@qq.com', 
            'name': '小明', 
            'friends': 
                [
                    {'name': '小红'}, 
                    {'name': '小白'}, 
                    {'name': '小黑'}
                ]
        }
    """

    return "hello"

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0" , port=5998)
